Scrutinizer GitHub App not installed

We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.

Install GitHub App

GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Branch master (5c2c02)
by Sebastian
03:02
created

dlfViewerSource.IIIF   C

Complexity

Conditions 8
Paths 4

Size

Total Lines 94

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
c 0
b 0
f 0
nc 4
nop 1
dl 0
loc 94
rs 5.4672

1 Function

Rating   Name   Duplication   Size   Complexity  
C 0 34 7

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
/**
2
 * (c) Kitodo. Key to digital objects e.V. <[email protected]>
3
 *
4
 * This file is part of the Kitodo and TYPO3 projects.
5
 *
6
 * @license GNU General Public License version 3 or later.
7
 * For the full copyright and license information, please read the
8
 * LICENSE.txt file that was distributed with this source code.
9
 */
10
11
/**
12
 * Namespace for dlfViewer ol3 sources
13
 * @namespace
14
 */
15
var dlfViewerSource = dlfViewerSource || {};
0 ignored issues
show
Bug introduced by
The variable dlfViewerSource seems to be never initialized.
Loading history...
16
17
/**
18
 * Utility Function based on Google Closure Library.
19
 * http://google.github.io/closure-library/api/source/closure/goog/object/object.js.src.html#l306
20
 *
21
 * Searches an object for an element that satisfies the given condition and
22
 * returns its key.
23
 *
24
 * @param {Object<K,V>} obj The object to search in.
25
 * @param {function(this:T,V,string,Object<K,V>):boolean} f The
26
 *      function to call for every element. Takes 3 arguments (the value,
27
 *     the key and the object) and should return a boolean.
28
 * @param {T=} opt_this An optional "this" context for the function.
29
 * @return {string|undefined} The key of an element for which the function
30
 *     returns true or undefined if no such element is found.
31
 */
32
dlfViewerSource.findKey = function(obj, f, opt_this) {
33
    for (var key in obj) {
0 ignored issues
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
34
        if (f.call(/** @type {?} */ (opt_this), obj[key], key, obj)) {
35
            return key;
36
        }
37
    }
38
    return undefined;
39
};
40
41
/**
42
 * OpenLayers 3 TileLoadFunction based on the work of Klokan Technologies GmbH (http://www.klokantech.com) and
43
 * the IIIFViewer. See: https://github.com/klokantech/iiifviewer/blob/master/src/iiifsource.js
44
 *
45
 * @param {number} tileSize
46
 * @param {ol.ImageTile} tile
47
 * @param {string} url
48
 */
49
dlfViewerSource.tileLoadFunction = function(tileSize, tile, url) {
50
    var img = tile.getImage();
51
    $(img).load(function() {
52
        if (img.naturalWidth > 0 &&
53
          (img.naturalWidth != tileSize || img.naturalHeight != tileSize)) {
54
            var canvas = document.createElement('canvas');
55
            canvas.width = tileSize;
56
            canvas.height = tileSize;
57
58
            var ctx = canvas.getContext('2d');
59
            ctx.drawImage(img, 0, 0);
60
61
            var key = dlfViewerSource.findKey(tile, function(v) {return v == img;});
62
            if (key) tile[key] = canvas;
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
63
        }
64
    })
65
    img.src = url;
66
};
67
68
/**
69
 * OpenLayers 3 compatible source object for an iiif server.
70
 *
71
 * Based on the work of Klokan Technologies GmbH (http://www.klokantech.com) and the IIIFViewer. See:
72
 * https://github.com/klokantech/iiifviewer/blob/master/src/iiifsource.js
73
 *
74
 * @param {Object} options
75
 * @constructor
76
 */
77
dlfViewerSource.IIIF = function(options) {
78
79
    // parse parameters
80
    var url = options.url,
81
        format = options.format !== undefined ? options.format : 'jpg',
82
        quality = options.quality !== undefined ? options.quality : 'native',
83
        width = options.size[0],
84
        height = options.size[1],
85
        tileSize = options.tileSize !== undefined ? options.tileSize : 256,
86
        origin = options.crossOrigin !== undefined ? options.crossOrigin : '*',
87
        offset = options.offset !==  undefined ? options.offset : [0, 0],
88
        resolutions = $.extend([], options.resolutions),
89
        projection = options.projection;
90
91
    // calculate custom paramters
92
    var maxZoom = Math.max(
93
        Math.ceil( Math.log(width / tileSize) / Math.LN2),
94
        Math.ceil( Math.log(height / tileSize) / Math.LN2)
95
    );
96
97
    var tierSizes = [];
98
    for (var i = 0; i <= maxZoom; i++) {
99
        var scale = Math.pow(2, maxZoom - i);
100
        var width_ = Math.ceil(width / scale);
101
        var height_ = Math.ceil(height / scale);
102
        var tilesX_ = Math.ceil(width_ / tileSize);
103
        var tilesY_ = Math.ceil(height_ / tileSize);
104
        tierSizes.push([tilesX_, tilesY_]);
105
    }
106
107
    // define tilegrid with offset extent
108
    var extent = [offset[0], offset[1] + -height, offset[0] + width, offset[1]];
109
    var tileGrid = new ol.tilegrid.TileGrid({
0 ignored issues
show
Bug introduced by
The variable ol seems to be never declared. If this is a global, consider adding a /** global: ol */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
110
            extent: extent,
111
            resolutions: resolutions.reverse(),
112
            origin: ol.extent.getTopLeft(extent),
113
            tileSize: tileSize
114
        });
115
116
    /**
117
     * @this {ol.source.TileImage}
118
     * @param {ol.TileCoord} tileCoord Tile Coordinate.
119
     * @param {number} pixelRatio Pixel ratio.
120
     * @param {ol.proj.Projection} projection Projection.
121
     * @return {string|undefined} Tile URL.
122
     */
123
    var tileUrlFunction = function(tileCoord, pixelRatio, projection) {
0 ignored issues
show
Unused Code introduced by
The parameter pixelRatio is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter projection is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
124
125
        var z = tileCoord[0];
126
        if (maxZoom < z) {
127
            return undefined;
128
        }
129
130
        var sizes = tierSizes[z];
131
        if (!sizes) {
132
            return undefined;
133
        }
134
135
        var x = tileCoord[1];
136
        var y = -tileCoord[2] - 1;
137
        if (x < 0 || sizes[0] <= x || y < 0 || sizes[1] <= y) {
138
            return undefined;
139
        } else {
140
            var scale = Math.pow(2, maxZoom - z);
141
            var tileBaseSize = tileSize * scale;
142
            var minx = x * tileBaseSize;
143
            var miny = y * tileBaseSize;
144
            var maxx = Math.min(minx + tileBaseSize, width);
145
            var maxy = Math.min(miny + tileBaseSize, height);
146
147
            maxx = scale * Math.floor(maxx / scale);
148
            maxy = scale * Math.floor(maxy / scale);
149
150
            var query = '/' + minx + ',' + miny + ',' +
151
              (maxx - minx) + ',' + (maxy - miny) +
152
              '/pct:' + (100 / scale) + '/0/' + quality + '.' + format;
153
154
            return url + query;
155
        }
156
    };
157
158
    var tileImageParams = {
159
        crossOrigin: origin,
160
        projection: projection,
161
        tileGrid: tileGrid,
162
        tileUrlFunction: tileUrlFunction
163
    };
164
165
    if (ol.has.CANVAS) {
0 ignored issues
show
Bug introduced by
The variable ol seems to be never declared. If this is a global, consider adding a /** global: ol */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
166
        tileImageParams.tileLoadFunction = dlfViewerSource.tileLoadFunction.bind(this, tileSize);
167
    }
168
169
    return new ol.source.TileImage(tileImageParams);
170
};
171
172
/**
173
 * Returns an iiif compatible metadata url.
174
 *
175
 * @param {string} baseUrl
176
 * @return {string}
177
 */
178
dlfViewerSource.IIIF.getMetdadataURL = function(baseUrl) {
179
    var pathString = baseUrl.lastIndexOf('/') + 1 === baseUrl.length
180
        ? 'info.json'
181
        : '/info.json';
182
183
    return baseUrl + pathString;
184
};
185
186
/**
187
 * OpenLayers 3 compatible source object for an iip server.
188
 *
189
 *
190
 * @param {Object} options
191
 * @constructor
192
 */
193
dlfViewerSource.IIP = function(options) {
194
195
    // parse parameters
196
    var url = options.url.indexOf('?') > -1
197
          ? options.url
198
          : options.url + '?',
199
        width = options.size[0],
200
        height = options.size[1],
201
        tileSize = options.tileSize !== undefined ? options.tileSize : 256,
202
        origin = options.crossOrigin !== undefined ? options.crossOrigin : '*',
203
        offset = options.offset !==  undefined ? options.offset : [0, 0],
204
        resolutions = [],
205
        projection = options.projection;
206
207
    // calculate tiersize in tiles and resolutions
208
    var tierSizeInTiles = [],
209
        imageWidth = width,
210
        imageHeight = height,
211
        res = 1;
212
    while (imageWidth > tileSize || imageHeight > tileSize) {
213
214
        tierSizeInTiles.push([
215
            Math.ceil(imageWidth / tileSize),
216
            Math.ceil(imageHeight / tileSize)
217
        ]);
218
        resolutions.push( res );
219
220
        imageWidth >>= 1;
221
        imageHeight >>= 1;
222
        res += res;
223
224
    };
225
    resolutions.push( res );
226
    tierSizeInTiles.push( [1,1]);
227
    tierSizeInTiles.reverse();
228
229
    var extent = [offset[0], offset[1] + -height, offset[0] + width, offset[1]];
230
    var tileGrid = new ol.tilegrid.TileGrid({
0 ignored issues
show
Bug introduced by
The variable ol seems to be never declared. If this is a global, consider adding a /** global: ol */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
231
        extent: extent,
232
        resolutions: resolutions.reverse(),
233
        origin: ol.extent.getTopLeft(extent),
234
        tileSize: tileSize
235
    });
236
237
    /**
238
     * @this {ol.source.TileImage}
239
     * @param {ol.TileCoord} tileCoord Tile Coordinate.
240
     * @param {number} pixelRatio Pixel ratio.
241
     * @param {ol.proj.Projection} projection Projection.
242
     * @return {string|undefined} Tile URL.
243
     */
244
    var tileUrlFunction = function(tileCoord, pixelRatio, projection) {
0 ignored issues
show
Unused Code introduced by
The parameter pixelRatio is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
Unused Code introduced by
The parameter projection is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
245
        if (tileCoord === undefined ||tileCoord === null) {
246
            return undefined;
247
        } else {
248
            var resolution = tileCoord[0],
249
                tileCoordX = tileCoord[1],
250
                tileCoordY = -tileCoord[2] - 1,
251
                tileIndex = tileCoordY * tierSizeInTiles[resolution][0] + tileCoordX;
252
            return url + '&JTL=' + resolution + ',' + tileIndex;
253
        }
254
    }
255
256
    var tileImageParams = {
257
        crossOrigin: origin,
258
        projection: projection,
259
        tileGrid: tileGrid,
260
        tileUrlFunction: tileUrlFunction
261
    };
262
263
    if (ol.has.CANVAS) {
0 ignored issues
show
Bug introduced by
The variable ol seems to be never declared. If this is a global, consider adding a /** global: ol */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
264
        tileImageParams.tileLoadFunction = dlfViewerSource.tileLoadFunction.bind(this, tileSize);
265
    }
266
267
    return new ol.source.TileImage(tileImageParams);
268
269
270
};
271
272
/**
273
 * Returns an iip compatible metadata url.
274
 *
275
 * @param {string} baseUrl
276
 * @return {string}
277
 */
278
dlfViewerSource.IIP.getMetdadataURL = function(baseUrl) {
279
    var queryString = '&obj=IIP,1.0&obj=Max-size&obj=Tile-size&obj=Resolution-number',
280
        url = baseUrl.indexOf('?') > -1
281
          ? baseUrl
282
          : baseUrl + '?';
283
    return url + queryString;
284
};
285
286
/**
287
 * Function parses a given string response for a iip metadata request.
288
 *
289
 * @param {string} metadataString
290
 * @return {Object}
291
 */
292
dlfViewerSource.IIP.parseMetadata = function(metadataString) {
293
294
    // parse size
295
    var maxSize = metadataString.split( "Max-size" );
296
    if(!maxSize[1]) {
297
        return null;
298
    }
299
    var size = maxSize[1].split(" ");
300
301
    // parse tile size
302
    var tileSizeTmp = metadataString.split( "Tile-size" );
303
    if(!tileSizeTmp[1]) {
304
        return null;
305
    }
306
    var tileSize = tileSizeTmp[1].split(" ");
307
308
    // parse resolution
309
    var resolutionNumTmp = metadataString.split( "Resolution-number"),
310
        resolutionNum = parseInt( resolutionNumTmp[1].substring(1,resolutionNumTmp[1].length)),
311
        res = 1,
312
        resolutions = [];
313
    for (var i = 0; i <resolutionNum; i++) {
314
        resolutions.push(res);
315
        res += res;
316
    }
317
318
    var metadataObj = {
319
        'width': parseInt(size[0].substring(1,size[0].length)),
320
        'height': parseInt(size[1]),
321
        'tilesize': [parseInt(tileSize[0].substring(1,tileSize[0].length)), parseInt(tileSize[1]) ],
322
        'resolutions': resolutions
323
    };
324
    return metadataObj;
325
};